<?php
class Controller_Land extends Controller_Client_Layout
{
    
    public function __construct(Request $request, Response $response) 
    {
        parent::__construct($request, $response);
        
        if(Request::current()->action() === 'post')
        {
            // required login
            if(!Api::load('user')->is_logged())
            {
                FlashMessage::getInstance()->add('Bạn cần đăng nhập để đăng tin trên Wharfland.');
                
                // Should be redirect to login page
                $this->request->redirect('/');
            }
        }
    }
    
	function action_detail($id = null)
	{
		if(is_null($id)){
			$this->response->status(404);
		}else{
            
            $land = Libs_Land::getInstance()->getLandById($id);
            
            if($land)
            {
                $user_land = Doctrine_Query::create()
                                ->from('Land l')
                                ->where('l.created_by = ?',$land->created_by)
                                ->whereNotIn('l.id',array($id))->limit(5)->execute();
                
                $related_land = Doctrine_Query::create()
                                        ->from('Land l')
                                        ->where('l.land_type_id = ?',$land->land_type_id)
                                        ->whereNotIn('l.id',array($land->id))
                                        ->limit(5)->execute();
            }
            
            $this->set_main_right(null);
            
			$this->set_contents(View::client('land/detail')->set(array(
				'land' => $land,
                'user_land' => isset($user_land) && count($user_land) > 0 ? $user_land : false,
                'related_land' => isset($related_land) && count($related_land) > 0 ? $related_land : false,
                'user' => UserTable::getInstance()->findOneById($land->created_by)
			)));
		}
	}
    
    function action_post()
    {
        $data = Arr::extract($_POST, array(
            'title','short_description','direction',
            'transaction_type','contact_name','contact_title','contact_phone',
            'price','area','description','location_id','land_type'
        ));
        
        if(Request::current()->method() === 'POST')
        {
            $valid = Validation::factory($data)
									->rule('title','not_empty')
									->rule('title','max_length',array('title',255))
									->rule('contact_name','not_empty')
									->rule('contact_phone','not_empty')
                                    ->rule('area','numeric');
            if($valid->check()){
                
                $saved = Libs_Land::getInstance()->saveLand($data);
                
                if(!$saved)
                    FlashMessage::getInstance ()->add('Đăng tin thất bại. Bạn vui lòng thử lại');
                else 
                    FlashMessage::getInstance ()->add('Tin của bạn đã đuợc đăng thành công.',  FlashMessage::SUCCESS);
                $this->request->redirect('/');
                
            }else{
                FlashMessage::getInstance()->add($valid->errors('land',true));
            }
        }
        
        $this->add_scripts(Url::client_assets().'js/autoNumeric.js');
        $this->add_scripts(Url::vendors().'tiny_mce/jquery.tinymce.js');
		$this->add_scripts(Url::client_assets().'js/tinymce.js');
        
    	$this->set_main_right(); //disable main_right column
          $this->set_contents(View::client('land/post')->set(array(
        	 'location' => Libs_Land::getInstance()->get_location(),
             'data' => $data
	    )));
    }
    
    public function action_page($page = null)
    {
        $this->set_contents(View::client('land/page')->set(array(
                'list' => Libs_Land::getInstance()->get_list('client/land/list')
            )));
    }
    
    /**
     * View list land by user
     * @param type $user 
     */
    public function action_by($user = null)
    {
        if(!is_null($user)){
            $user = UserTable::getInstance()->findOneByUsername($user);
            if($user){
                $this->set_contents(View::client('land/by')->set(array(
                    'list_land' => Libs_Land::getInstance()->get_list('client/land/list'),
                    'user' => $user
                )));
            }
            else{
                $this->response->status(404);
            }
        }else{
            $this->response->status(404);
        }
    }
    
    public function action_search()
    {
        $params = $this->get_search_query_params();
                
        $this->set_contents(View::client('land/search')->set(array(
            'list' => Libs_Land::getInstance()->get_list('client/land/list',$params)
        )));
    }
    
    
    /**
     * @todo get current query param from search form with xss clean
     * @return type
     */
    private function get_search_query_params()
    {
        $query_params = array(
            'direction','location','transaction_type','from_price',
            'to_price','area','land_type','operator'
        );
        
        $post = array();
        if(Request::current()->method() === "POST")
        {
            foreach($query_params as $param)
            {
                $post[$param] = Security::xss_clean(Arr::get($_POST,$param));
            }
            Session::instance()->set('query',  serialize($post));
        }else
        {
            if(!is_null($query = Session::instance()->get('query'))){
                $post = unserialize($query);
            }
        }
        
        return $post;
    }
}